package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import com.yt.sys.models.service.IRolePermissionService;
import com.yt.sys.models.service.IPermissionService;
import com.yt.sys.models.bo.RolePermissionBO;
import com.yt.sys.models.bo.RolePermissionAssignBO;
import com.yt.sys.models.dto.RolePermissionDTO;
import com.yt.sys.models.dto.PermissionDTO;
import com.yt.sys.models.vo.PermissionVO;

/**
 * 角色权限关联信息控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:47:57
 */

@RestController
@RequestMapping("/api/rolePermission")
@Slf4j
@Api(value = "RolePermissionApiController",tags = "角色权限关联信息Api接口")
public class RolePermissionApiController {

    @DubboReference
    private IRolePermissionService rolePermissionService;
    
    @DubboReference
    private IPermissionService permissionService;

    @PostMapping("/assign")
    @ApiOperation(value = "为指定角色分配权限", notes = "为指定角色分配权限")
    public Result assignPermissions(@RequestBody RolePermissionAssignBO assignBO) {
        // 参数校验
        if (StrUtils.isEmpty(assignBO.getRoleId()) || assignBO.getPermissionIds() == null) {
            return new Result(CodeEnum.FAIL_100002);
        }
        
        // 先删除角色原有的权限关联
        Wrapper<RolePermissionDTO> deleteWrapper = new EntityWrapper<>();
        deleteWrapper.eq("role_id", assignBO.getRoleId());
        rolePermissionService.delete(deleteWrapper);
        
        // 批量插入新的角色权限关联
        List<RolePermissionDTO> rolePermissionList = new ArrayList<>();
        for (String permissionId : assignBO.getPermissionIds()) {
            RolePermissionDTO rolePermission = new RolePermissionDTO();
            rolePermission.setRoleId(assignBO.getRoleId());
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }
        
        if (!rolePermissionList.isEmpty()) {
            rolePermissionService.insertBatch(rolePermissionList);
        }
        
        return new Result();
    }

    @PostMapping("/{roleId}/permissions")
    @ApiOperation(value = "获取指定角色已分配的权限列表", notes = "获取指定角色已分配的权限列表")
    public Result<List<PermissionVO>> getRolePermissions(@PathVariable("roleId") String roleId) {
        // 查询角色关联的权限ID列表
        Wrapper<RolePermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        List<RolePermissionDTO> rolePermissionList = rolePermissionService.selectList(wrapper);
        
        // 提取权限ID列表
        List<String> permissionIds = rolePermissionList.stream()
                .map(RolePermissionDTO::getPermissionId)
                .collect(Collectors.toList());
        
        // 如果没有权限，返回空列表
        if (permissionIds.isEmpty()) {
            return new Result<>();
        }
        
        // 根据权限ID列表查询权限详情
        Wrapper<PermissionDTO> permissionWrapper = new EntityWrapper<>();
        permissionWrapper.in("id", permissionIds);
        List<PermissionDTO> permissionList = permissionService.selectList(permissionWrapper);
        
        // 转换为VO对象
        List<PermissionVO> permissionVOList = permissionList.stream().map(permission -> {
            PermissionVO vo = new PermissionVO();
            vo.setId(String.valueOf(permission.getId())); // 修复类型转换问题
            vo.setPermissionName(permission.getPermissionName());
            vo.setPermissionCode(permission.getPermissionCode());
            vo.setType(permission.getType());
            vo.setUrl(permission.getUrl());
            vo.setStatus(permission.getStatus());
            return vo;
        }).collect(Collectors.toList());
        
        return new Result<>(permissionVOList);
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<RolePermissionDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        RolePermissionDTO dto = rolePermissionService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "角色权限关联信息列表",notes = "角色权限关联信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<RolePermissionDTO>> queryPageList(RolePermissionBO bo){
        Wrapper<RolePermissionDTO> wrapper = new EntityWrapper<>();
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<RolePermissionDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = rolePermissionService.selectPage(page, wrapper);

        return new Result<>(page);
    }
}